package com.car.carsharing.service.impl;

import com.car.carsharing.mapper.CouponMapper;
import com.car.carsharing.mapper.UserCouponMapper;
import com.car.carsharing.pojo.Coupon;
import com.car.carsharing.pojo.UserCoupon;
import com.car.carsharing.service.UserCouponService;
import com.car.carsharing.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserCouponServiceImpl implements UserCouponService {
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Override
    public Integer buyCoupon(Integer userId, Integer couponId) {
        String time = StringUtils.getTime(new Date());

        //获取优惠卷过期时间
        Coupon coupon = couponMapper.selectCoupon(couponId);
        String effectiveTime = coupon.getEffectiveTime();

        //不能重复购买
        UserCoupon uc = new UserCoupon();
        uc.setUserId(userId);
        uc.setCouponId(couponId);
        uc.setEffectiveTime(effectiveTime);
        UserCoupon userCoupon = userCouponMapper.selectUserCoupon(uc);
        if(userCoupon != null){
            return -1;
        }

        return userCouponMapper.buyCoupon(userId,couponId,time,effectiveTime);
    }
}
